<?php
namespace app\console\controller;

use app\console\model\NewsType as NewsTypeModel;;
use app\console\model\News;;
use think\Validate;
use think\Request;

class NewsType extends Base
{

    public function index(Request $request)
    {
        $map = [];
        if (!empty($this->request->param('status'))) {
            $map['status'] = $this->request->param('status');
        } 
        $data = array_filter($request->get());
        if (!empty($data['search']) && !empty($data['key'])) {
            $map[$data['search']] = array('like', "%{$data['key']}%");
        }

        $list = NewsTypeModel::order('sort asc')->where($map)->paginate(20);
        // dump(json_decode( json_encode( $list),true));exit;

        return view('index', compact('list'));
    }

    public function add()
    {
        return view('add');
    }

    public function add_post()
    {
        $validate = new Validate(
            [
                ['name','require','分类名称不能为空'],
                ['sort','require','排序不能为空'],
            ]
        );
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $res['title'] = $validate->getError();
            $res['type'] = 'error';
            return success($res);
        }

        NewsTypeModel::create([
            'name' => $data['name'],
            'sort' => $data['sort'],
            'status' => $data['status'],
        ]);

        $res['url'] = url('console/news_type/index');
        $res['title'] = '添加分类成功';
        $res['type'] = 'success';

        return success($res);

    }

    public function edit($id)
    {
        $detail = NewsTypeModel::find($id);

        return view('edit', compact('detail'));
    }

    // 更新轮播图
    public function edit_post()
    {
        $validate = new Validate(
            [
                ['name','require','分类名称不能为空'],
                ['sort','require','排序不能为空'],
            ]
        );
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $res['name'] = $validate->getError();
            $res['type'] = 'error';
            return success($res);
        }

        $user = NewsTypeModel::get($data['id']);

        $user->name   = $data['name'];
        $user->sort   = $data['sort'];
        $user->status   = $data['status'];
        $user->save();


        $res['url'] = url('console/news_type/index');
        $res['title'] = '更新成功';
        $res['type'] = 'success';

        return success($res);
    }

    public function delete()
    {
        $id = $this->request->param('id');
        
        NewsTypeModel::destroy($id);
        $res['url'] = url('console/news_type/index');
        $res['title'] = '删除成功';
        $res['type'] = 'success';

        return success($res);

    }
}
